package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.IUserDao;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.IncomeBasicInfoMapper;
import com.koocloud.electroplatemanage.mapper.IncomePartJudgeMapper;
import com.koocloud.electroplatemanage.mapper.MainProductionMapper;
import com.koocloud.electroplatemanage.mapper.ProcessMapper;
import com.koocloud.electroplatemanage.pojo.IncomeBasicInfoVo;
import com.koocloud.electroplatemanage.pojo.IncomePartJudgeVo;
import com.koocloud.electroplatemanage.pojo.Process;
import com.koocloud.electroplatemanage.pojo.User;
import com.koocloud.electroplatemanage.pojo.mainpojo.OrderResource;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.IncomeBasicInfoService;
import com.koocloud.electroplatemanage.utils.ListUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.*;
import static com.koocloud.electroplatemanage.constant.IncomePartJudgeSqlFieldConstant.ZERO;

/**
 * @program: Information_platform
 * @description: 来件基础信息实现层
 * @author: xxc
 * @create: 2020-11-13 14:59
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class IncomeBasicInfoServiceImpl implements IncomeBasicInfoService {
    @Resource
    private IUserDao iUserDao;
    @Resource
    private IncomeBasicInfoMapper incomeBasicInfoMapper;
    @Resource
    private MainProductionMapper mainProductionMapper;
    @Resource
    private IncomePartJudgeMapper incomePartJudgeMapper;
    @Resource
    private ProcessMapper processMapper;
    Lock lock=new ReentrantLock();

    /**
     *@Description: 通过工单号查询来件基本信息
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/13
     */
    @Override
    public ResponseTemplate selectByWorkOrderNumber(String workOrderNumber) {
        try {
            //创建来件基本信息实体
            IncomeBasicInfoVo incomeBasicInfoVo = incomeBasicInfoMapper.selectIncomeBasicInfo(workOrderNumber);
            //判断查表操作是否成功
            if (null != incomeBasicInfoVo) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(incomeBasicInfoVo).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }

    }

    /**
     *@Description: 对来件基础信息进行全表查询
     *@Param: [page, limit, incomeBasicInfoVo]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/13
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit, IncomeBasicInfoVo incomeBasicInfoVo) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                lock.lock();
                int rows = -1;
                //开始查询在工表，状态为2的插入来料基本信息
                List<WIP> wipList= mainProductionMapper.selectAllWIPByLocation(INCOMEPARTENTRY);
                if(!StringUtils.isEmpty(wipList)) {
                    for(WIP wip:wipList) {
                        //获取工单号
                        if(!StringUtils.isEmpty(wip.getWorkOrderNumber())) {
                            //数据库重复工单号校验
                            int count = incomeBasicInfoMapper.selectWorkOrderNumberCount(wip.getWorkOrderNumber());
                            if(count>0) {
                                continue;
                            }


                            IncomeBasicInfoVo insertBasicInfo = new IncomeBasicInfoVo();
                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置创建人
                                insertBasicInfo.setCreator(wip.getEntryPerson());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置创建时间
                                insertBasicInfo.setCreateTime(wip.getEntryTime());
                            }
                            String workOrderNumber = wip.getWorkOrderNumber();
                            //设置工单号
                            insertBasicInfo.setWorkOrderNumber(workOrderNumber);
                            //根据工单号查询台账表记录
                            IncomePartJudgeVo incomePartJudgeVo = incomePartJudgeMapper.selectByWorkOrderNumber(workOrderNumber);

                            if(!StringUtils.isEmpty(incomePartJudgeVo)) {
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartUnitCode())) {
                                    //设置来件单位编码
                                    insertBasicInfo.setCustomerName(incomePartJudgeVo.getIncomePartUnitCode());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getOrderNumber())) {
                                    //设置批次编号
                                    insertBasicInfo.setBatchNumber(incomePartJudgeVo.getOrderNumber());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getPartName())) {
                                    //设置零部件名称
                                    insertBasicInfo.setPartName(incomePartJudgeVo.getPartName());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getDrawNoCode())) {
                                    //设置零部件图号
                                    insertBasicInfo.setDrawNoCode(incomePartJudgeVo.getDrawNoCode());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartQuantity())) {
                                    //设置来件数量
                                    insertBasicInfo.setIncomePartQuantity(incomePartJudgeVo.getIncomePartQuantity());
                                }
                                rows=incomeBasicInfoMapper.insert(insertBasicInfo);
                                //记录成功插入条数
                            }

                        }
                    }
                }
                //在工表插入完成后开始查询
                if(StringUtils.isEmpty(wipList)||(wipList.size()>0&&rows>0)||(wipList.size()>=0&&rows==-1)) {
                    //开始分页
                    PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                    //全局查询
                    List<IncomeBasicInfoVo> IncomeBasicInfoVoList = incomeBasicInfoMapper.selectAllData(incomeBasicInfoVo);
                    //构造分页实体
                    PageInfo<IncomeBasicInfoVo> info=new PageInfo<>(IncomeBasicInfoVoList);
                    if (info.getTotal()>0) {
                        //查询到数据
                        return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                    } else {
                        //没有查询到数据
                        return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                    }
                }

                else {
                    return ResponseTemplate.builder().code(1).message("在工表数据导入失败").count(0l).build();
                }

            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
            finally {
                lock.unlock();
            }
        } else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    /**
     *@Description: 新增一条来件基础信息数据
     *@Param: [incomeBasicInfoVo]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/13
     */
    @Override
    public ResponseTemplate insert(IncomeBasicInfoVo incomeBasicInfoVo,String userId) {
        try{
            lock.lock();
            //获取创建人
            User user = iUserDao.selectByPk(userId);
            //设置创建人
            incomeBasicInfoVo.setCreator(user.getJobNum());
            //插入一条记录
            int row = incomeBasicInfoMapper.insert(incomeBasicInfoVo);

            if (row > 0) {
                return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
            } else {//没有异常并且插入数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 逻辑删除一条记录
     *@Param: [id, userId, deleteFlag]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/13
     */
    @Override
    public ResponseTemplate delete(String id, String userId, String deleteFlag) {
        try {
            lock.lock();
            //获取修改人
            User user = iUserDao.selectByPk(userId);
            //逻辑删除一条记录
            int rows = incomeBasicInfoMapper.delete(id,user.getJobNum(),deleteFlag);
            //判断删除操作是否成功
            if (rows > 0) {
                //删除成功返回数据
                return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
            } else {
                //删除失败返回提示
                return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }


    /**
     *@Description: 修改一条来件基础信息记录
     *@Param: [incomeBasicInfoVo, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/13
     */
    @Override
    public ResponseTemplate update(IncomeBasicInfoVo incomeBasicInfoVo, String userId) {
        try {
            lock.lock();
            //获取修改人
            User user = iUserDao.selectByPk(userId);
            //设置修改人
            incomeBasicInfoVo.setModifier(user.getJobNum());
            incomeBasicInfoVo.setDeleteFlag("2");
            //没有异常并且修改数据条数大于0
            int row = incomeBasicInfoMapper.update(incomeBasicInfoVo);

            if(row > 0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }

    /**
     *@Description:  来件基本信息确认
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/18
     */
    @Override
    public ResponseTemplate confirmEntryInfo(String workOrderNumber,String userId) {
        try{
            lock.lock();
            //操作人
            User user = iUserDao.selectByPk(userId);
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String strDate = df.format(date);//获取String类型的时间
            //改变来件基础信息表的状态
            incomeBasicInfoMapper.changeState(workOrderNumber);
            //查看历史信息
            IncomeBasicInfoVo incomeBasicInfoVo = incomeBasicInfoMapper.selectIncomeBasicInfo(workOrderNumber);
            List<IncomeBasicInfoVo> incomeBasicInfoVoPastRecords = null;
            if (!StringUtils.isEmpty(incomeBasicInfoVo)){
                incomeBasicInfoVoPastRecords = incomeBasicInfoMapper.selectPastRecords(workOrderNumber,incomeBasicInfoVo.getDrawNoName(),incomeBasicInfoVo.getPartName(),incomeBasicInfoVo.getDrawEdition());
            }
            int rows = 0;
            int row = 0;
            if (!ListUtil.isEmpty(incomeBasicInfoVoPastRecords)) {
                //生产在工表
                WIP wip = mainProductionMapper.selectWIPByPk(workOrderNumber);
                wip.setCurrentLocation(PROCESSPREPARATION);
                wip.setLine(incomeBasicInfoVo.getLine());
                rows =  mainProductionMapper.updateWIP(wip);
                //生产实际表
                String postion = INCOMEPARTENTRY;
                List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(workOrderNumber,postion);
                OrderResource orderResource = orderResourceList.get(0);
                //上一状态完成时间
                orderResource.setCompletionTime(strDate);
                //上一状态完成人
                orderResource.setCompletedPerson(user.getJobNum());
                mainProductionMapper.updateOrderResource(orderResource);
                orderResource.setRoutePosition(PROCESSPREPARATION);
                //投入时间
                orderResource.setEntryTime(strDate);
                //投入人
                orderResource.setEntryPerson(user.getJobNum());
                //上一状态完成时间
                orderResource.setCompletionTime(strDate);
                //上一状态完成人
                orderResource.setCompletedPerson(user.getJobNum());
                orderResource.setLine(incomeBasicInfoVo.getLine());
                Process process = processMapper.selectByWorkOrderNumber(incomeBasicInfoVoPastRecords.get(Integer.parseInt(ZERO)).getWorkOrderNumber());
                Process insertProcess = new Process();
                if(!StringUtils.isEmpty(process.getCreator())) {
                    //设置制单人
                    insertProcess.setCreator(process.getCreator());
                }
                if(!StringUtils.isEmpty(process.getCreateTime())) {
                    //设置制单时间
                    insertProcess.setCreateTime(process.getCreateTime());
                }
                if(!StringUtils.isEmpty(process.getCheck())) {
                    //设置验收
                    insertProcess.setCreator(process.getCheck());
                }
                if(!StringUtils.isEmpty(process.getProcessSpecification())) {
                    //设置工艺规程
                    insertProcess.setCreateTime(process.getProcessSpecification());
                }
                if(!StringUtils.isEmpty(process.getTest())) {
                    //设置检验
                    insertProcess.setCreator(process.getTest());
                }
                if(!StringUtils.isEmpty(process.getTransferWork())) {
                    //设置转工
                    insertProcess.setCreateTime(process.getTransferWork());
                }
                if(!StringUtils.isEmpty(process.getOther())) {
                    //设置其他
                    insertProcess.setCreateTime(process.getOther());
                }
                //设置工单号
                insertProcess.setWorkOrderNumber(workOrderNumber);
                rows = processMapper.insert(insertProcess);

                mainProductionMapper.insertOrderResource(orderResource);
                //投入时间
                orderResource.setEntryTime(strDate);
                //投入人
                orderResource.setEntryPerson(user.getJobNum());
                //完成时间
                orderResource.setCompletionTime(null);
                //完成人
                orderResource.setCompletedPerson(null);
                orderResource.setRoutePosition(SCHEDULING);
                row = mainProductionMapper.insertOrderResource(orderResource);
            }else {
                /*//工单号表
            WorkOrder workOrder = mainProductionMapper.selectWorkOrderByPk(workOrderNumber);
            workOrder.setCurrentLocation(PROCESSPREPARATION);
            int limit = mainProductionMapper.updateWorkOrder(workOrder);*/
                //生产在工表
                WIP wip = mainProductionMapper.selectWIPByPk(workOrderNumber);
                wip.setCurrentLocation(PROCESSPREPARATION);
                wip.setLine(incomeBasicInfoVo.getLine());
                rows =  mainProductionMapper.updateWIP(wip);
                //生产实际表
                String postion = INCOMEPARTENTRY;
                List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(workOrderNumber,postion);
                OrderResource orderResource = orderResourceList.get(0);
                //上一状态完成时间
                orderResource.setCompletionTime(strDate);
                //上一状态完成人
                orderResource.setCompletedPerson(user.getJobNum());
                mainProductionMapper.updateOrderResource(orderResource);
                orderResource.setRoutePosition(PROCESSPREPARATION);
                //投入时间
                orderResource.setEntryTime(strDate);
                //投入人
                orderResource.setEntryPerson(user.getJobNum());
                //完成时间
                orderResource.setCompletionTime(null);
                //完成人
                orderResource.setCompletedPerson(null);
                orderResource.setLine(incomeBasicInfoVo.getLine());
                row = mainProductionMapper.insertOrderResource(orderResource);
            }

            if(rows>0 && row >0) {
                return ResponseTemplate.builder().code(0).message("确认成功").count(1l).build();
            } else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("确认失败").count(0l).build();
            }
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }

    }

    /**
     *@Description: 保存图片
     *@Param: [file]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/19
     */
    @Override
    public ResponseTemplate insertImg(String file) {
        try{
            lock.lock();
            int count = incomeBasicInfoMapper.selectImgIdCount(file);
            int id = 0;
            if (count > 0 ){
                id = incomeBasicInfoMapper.selectImgId(file);
            }else {
                incomeBasicInfoMapper.insertImg(file);
                id = incomeBasicInfoMapper.selectImgId(file);
            }
            LinkedHashMap linkedHashMap = new LinkedHashMap();
            linkedHashMap.put("id",id);
            return ResponseTemplate.builder().code(0).message("保存成功").data(linkedHashMap).count(0l).build();
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }


}
